import {PathRegConst, isNone, isEmpty, isStr} from 'st-common-core'
import {MenuTypeEnum, MenuObjPropNameEnum} from '@menu'
import {MenuIptLimit} from '../consts/menu-ipt-limit.ts'

// 菜单名称校验处理函数
const menuNameVerifyHandler = async (form: Record<string, any>) =>
  !isNone(form[MenuObjPropNameEnum.NAME]) &&
  isStr(form[MenuObjPropNameEnum.NAME]) &&
  !isEmpty(form[MenuObjPropNameEnum.NAME]) &&
  form[MenuObjPropNameEnum.NAME].length <= MenuIptLimit.NAME_MAX_LEN
// 菜单页面路径校验处理函数
const menuPagePathVerifyHandler = async (form: Record<string, any>) =>
  !isNone(form[MenuObjPropNameEnum.PAGE_PATH]) &&
  isStr(form[MenuObjPropNameEnum.PAGE_PATH]) &&
  !isEmpty(form[MenuObjPropNameEnum.PAGE_PATH]) &&
  form[MenuObjPropNameEnum.PAGE_PATH].length <= MenuIptLimit.PAGE_PATH_MAX_LEN &&
  PathRegConst.VUE_COMPONENT_PATH_REG.test(form[MenuObjPropNameEnum.PAGE_PATH])
// 菜单路由名称校验处理函数
const menuRouteNameVerifyHandler = async (form: Record<string, any>) =>
  !isNone(form[MenuObjPropNameEnum.ROUTE_NAME]) &&
  isStr(form[MenuObjPropNameEnum.ROUTE_NAME]) &&
  !isEmpty(form[MenuObjPropNameEnum.ROUTE_NAME]) &&
  form[MenuObjPropNameEnum.ROUTE_NAME].length <= MenuIptLimit.ROUTE_NAME_MAX_LEN
// 菜单路由路径校验处理函数
const menuRoutePathVerifyHandler = async (form: Record<string, any>) =>
  !isNone(form[MenuObjPropNameEnum.ROUTE_PATH]) &&
  isStr(form[MenuObjPropNameEnum.ROUTE_PATH]) &&
  !isEmpty(form[MenuObjPropNameEnum.ROUTE_PATH]) &&
  form[MenuObjPropNameEnum.ROUTE_PATH].length <= MenuIptLimit.ROUTE_PATH_MAX_LEN &&
  PathRegConst.ROUTE_PATH_REG.test(form[MenuObjPropNameEnum.ROUTE_PATH])
// 菜单链接路径校验处理函数
const menuLinkPathVerifyHandler = async (form: Record<string, any>) =>
  !isNone(form[MenuObjPropNameEnum.LINK_PATH]) &&
  isStr(form[MenuObjPropNameEnum.LINK_PATH]) &&
  !isEmpty(form[MenuObjPropNameEnum.LINK_PATH]) &&
  PathRegConst.LINK_PATH_REG.test(form[MenuObjPropNameEnum.LINK_PATH])

/**
 * 菜单类型为目录时，表单信息数据校验
 */
export const DirFormVerify = {
  [MenuObjPropNameEnum.NAME]: menuNameVerifyHandler,
  [MenuObjPropNameEnum.ROUTE_PATH]: menuRoutePathVerifyHandler,
}

/**
 * 菜单类型为菜单时，表单信息数据校验
 */
export const MenuFormVerify = {
  [MenuObjPropNameEnum.NAME]: menuNameVerifyHandler,
  [MenuObjPropNameEnum.PAGE_PATH]: menuPagePathVerifyHandler,
  [MenuObjPropNameEnum.ROUTE_NAME]: menuRouteNameVerifyHandler,
  [MenuObjPropNameEnum.ROUTE_PATH]: menuRoutePathVerifyHandler,
}

/**
 * 菜单类型为 iframe 时，表单信息数据校验
 */
export const IframeFormVerify = {
  [MenuObjPropNameEnum.NAME]: menuNameVerifyHandler,
  [MenuObjPropNameEnum.LINK_PATH]: menuLinkPathVerifyHandler,
}

/**
 * 菜单类型为外链时，表单信息数据校验
 */
export const LinkFormVerify = {
  [MenuObjPropNameEnum.NAME]: menuNameVerifyHandler,
  [MenuObjPropNameEnum.LINK_PATH]: menuLinkPathVerifyHandler,
}

/**
 * 菜单类型与相应菜单类型的表单信息数据校验之间的映射关系
 */
export const FormVerifyMap = {
  [MenuTypeEnum.DIR]: DirFormVerify,
  [MenuTypeEnum.MENU]: MenuFormVerify,
  [MenuTypeEnum.IFRAME]: IframeFormVerify,
  [MenuTypeEnum.LINK]: LinkFormVerify
}
